package com.service.dictionary;

import com.entity.dictionary.Department;
import com.facade.dictionary.dept.IDepartmentFacadeR;
import com.mapper.CustomMapper;
import com.mapper.dictionary.DepartmentMapper;
import com.service.CustomServiceR;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DepartmentServiceR extends CustomServiceR<Department> implements IDepartmentFacadeR {

    @Resource
    private DepartmentMapper mapper;

    @Override
    protected CustomMapper<Department> initMapper() {
        return mapper;
    }

    @Override
    public List<Department> findRankAll(String... sortOrder) {
        List<Department> departmentList = findAll(sortOrder);
        List<Department> topDepartmentList = new ArrayList<>();
        List<Department> recursiveDepartmentList = new ArrayList<>();
        for (Department department : departmentList) {
            department.setParents(findFullPropertyText(department.getPid(), "pid", "name", " - ", true));
            if (null != department.getPid()) {
                recursiveDepartmentList.add(department);
            } else {
                topDepartmentList.add(department);
            }
        }
        for (Department topDepartment : topDepartmentList) {
            departmentRank(topDepartment, recursiveDepartmentList);
        }
        return topDepartmentList;
    }

    private void departmentRank(Department department, List<Department> departmentList) {
        for (Department _$0 : departmentList) {
            if (department.getId().equals(_$0.getPid())) {
                department.getChildren().add(_$0);
                departmentRank(_$0, departmentList);
            }
        }
    }
}